<!DOCTYPE HTML>
<html lang="en-US" >
    
    <head>
        
        <meta charset="UTF-8">
        <title>构造方法 | OC中的私有方法</title>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="generator" content="GitBook 1.0.3">
        <meta name="HandheldFriendly" content="true"/>
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <link rel="apple-touch-icon-precomposed" sizes="152x152" href="gitbook/images/apple-touch-icon-precomposed-152.png">
        <link rel="shortcut icon" href="gitbook/images/favicon.ico" type="image/x-icon">
        
    
    
    
    <link rel="next" href="./10.html" />
    
    
    <link rel="prev" href="./new/README.html" />
    

        
    </head>
    <body>
        
        
<link rel="stylesheet" href="gitbook/style.css">


        
    <div class="book"  data-level="7" data-basepath="." data-revision="1442488483454">
    

<div class="book-summary">
    <div class="book-search">
        <input type="text" placeholder="Type to search" class="form-control" />
    </div>
    <ul class="summary">
        
    	
    	
    	

        

        
    
        
        <li class="chapter " data-level="0" data-path="index.html">
            
                
                    <a href="./index.html">
                        <i class="fa fa-check"></i>
                        
                         OC中的私有方法 
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="1" data-path="property/README.html">
            
                
                    <a href="./property/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>1.</b>
                        
                         @property基本概念 
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="2" data-path="synthesize/README.html">
            
                
                    <a href="./synthesize/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>2.</b>
                        
                         @synthesize基本概念
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="3" data-path="5.html">
            
                
                    <a href="./5.html">
                        <i class="fa fa-check"></i>
                        
                            <b>3.</b>
                        
                         @property增强
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="4" data-path="6.html">
            
                
                    <a href="./6.html">
                        <i class="fa fa-check"></i>
                        
                            <b>4.</b>
                        
                         @property修饰符
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="5" data-path="id/README.html">
            
                
                    <a href="./id/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>5.</b>
                        
                         id类型
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="6" data-path="new/README.html">
            
                
                    <a href="./new/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>6.</b>
                        
                         new方法实现原理
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter active" data-level="7" data-path="9.html">
            
                
                    <a href="./9.html">
                        <i class="fa fa-check"></i>
                        
                            <b>7.</b>
                        
                         构造方法
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="8" data-path="10.html">
            
                
                    <a href="./10.html">
                        <i class="fa fa-check"></i>
                        
                            <b>8.</b>
                        
                         自定义构造方法
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="9" data-path="12.html">
            
                
                    <a href="./12.html">
                        <i class="fa fa-check"></i>
                        
                            <b>9.</b>
                        
                         继承中的自定义构造方法
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="10" data-path="13.html">
            
                
                    <a href="./13.html">
                        <i class="fa fa-check"></i>
                        
                            <b>10.</b>
                        
                         自定义类工厂方法
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="11" data-path="1.html">
            
                
                    <a href="./1.html">
                        <i class="fa fa-check"></i>
                        
                            <b>11.</b>
                        
                         类的本质
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="12" data-path="14.html">
            
                
                    <a href="./14.html">
                        <i class="fa fa-check"></i>
                        
                            <b>12.</b>
                        
                         类的启动过程
                    </a>
                
            
            
        </li>
    
        
        <li class="chapter " data-level="13" data-path="sel/README.html">
            
                
                    <a href="./sel/README.html">
                        <i class="fa fa-check"></i>
                        
                            <b>13.</b>
                        
                         SEL类型
                    </a>
                
            
            
        </li>
    


        
        <li class="divider"></li>
        <li>
            <a href="http://www.gitbook.io/" target="blank" class="gitbook-link">Published using GitBook</a>
        </li>
        
    </ul>
</div>

    <div class="book-body">
        <div class="body-inner">
            <div class="book-header">
    <!-- Actions Left -->
    <a href="#" class="btn pull-left toggle-summary" aria-label="Toggle summary"><i class="fa fa-align-justify"></i></a>
    <a href="#" class="btn pull-left toggle-search" aria-label="Toggle search"><i class="fa fa-search"></i></a>
    
    <div id="font-settings-wrapper" class="dropdown pull-left">
        <a href="#" class="btn toggle-dropdown" aria-label="Toggle font settings"><i class="fa fa-font"></i>
        </a>
        <div class="dropdown-menu font-settings">
    <div class="dropdown-caret">
        <span class="caret-outer"></span>
        <span class="caret-inner"></span>
    </div>

    <div class="buttons">
        <button type="button" id="reduce-font-size" class="button size-2">A</button>
        <button type="button" id="enlarge-font-size" class="button size-2">A</button>
    </div>

    <div class="buttons font-family-list">
        <button type="button" data-font="0" class="button">Serif</button>
        <button type="button" data-font="1" class="button">Sans</button>
    </div>

    <div class="buttons color-theme-list">
        <button type="button" id="color-theme-preview-0" class="button size-3" data-theme="0">White</button>
        <button type="button" id="color-theme-preview-1" class="button size-3" data-theme="1">Sepia</button>
        <button type="button" id="color-theme-preview-2" class="button size-3" data-theme="2">Night</button>
    </div>
</div>

    </div>

    <!-- Actions Right -->
    
    <div class="dropdown pull-right">
        <a href="#" class="btn toggle-dropdown" aria-label="Toggle share dropdown"><i class="fa fa-share-alt"></i>
        </a>
        <div class="dropdown-menu font-settings dropdown-left">
            <div class="dropdown-caret">
                <span class="caret-outer"></span>
                <span class="caret-inner"></span>
            </div>
            <div class="buttons">
                <button type="button" data-sharing="twitter" class="button">Twitter</button>
                <button type="button" data-sharing="google-plus" class="button">Google</button>
                <button type="button" data-sharing="facebook" class="button">Facebook</button>
                <button type="button" data-sharing="weibo" class="button">Weibo</button>
                <button type="button" data-sharing="instapaper" class="button">Instapaper</button>
            </div>
        </div>
    </div>
    

    
    <a href="#" target="_blank" class="btn pull-right google-plus-sharing-link sharing-link" data-sharing="google-plus" aria-label="Share on Google Plus"><i class="fa fa-google-plus"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right facebook-sharing-link sharing-link" data-sharing="facebook" aria-label="Share on Facebook"><i class="fa fa-facebook"></i></a>
    
    
    <a href="#" target="_blank" class="btn pull-right twitter-sharing-link sharing-link" data-sharing="twitter" aria-label="Share on Twitter"><i class="fa fa-twitter"></i></a>
    
    

    <!-- Title -->
    <h1>
        <i class="fa fa-circle-o-notch fa-spin"></i>
        <a href="./" >OC中的私有方法</a>
    </h1>
</div>

            <div class="page-wrapper" tabindex="-1">
                <div class="page-inner">
                
                
                    <section class="normal" id="section-gitbook_343">
                    
                        <h1 id="">构造方法</h1>
<h2 id="">本小节知识:</h2>
<ol>
<li>【掌握】重写init方法</li>
<li>【理解】练习</li>
<li>【掌握】构造方法使用注意</li>
<li>【掌握】instancetype的作用</li>
</ol>
<hr>
<h2 id="1init">1.重写init方法</h2>
<ul>
<li><p>想在对象创建完毕后，成员变量马上就有一些默认的值就可以重写init方法</p>
</li>
<li><p>重写init方法格式:</p>
</li>
</ul>
<pre><code class="lang-objc">- (<span class="hljs-keyword">id</span>)init {
    <span class="hljs-keyword">self</span> = [<span class="hljs-keyword">super</span> init];
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">self</span>) {
        <span class="hljs-comment">// Initialize self.</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>;
}
</code></pre>
<pre><code>+ [super init]的作用:
</code></pre><p>面向对象的体现,先利用父类的init方法为子类实例的父类部分属性初始化。</p>
<pre><code>+ self 为什么要赋值为[super init]:
</code></pre><p>简单来说是为了防止父类的初始化方法release掉了self指向的空间并重新alloc了一块空间。还有[super init]可能alloc失败,这时就不再执行if中的语句。</p>
<ul>
<li>重写init方法其它格式</li>
</ul>
<pre><code class="lang-objc">- (<span class="hljs-keyword">id</span>)init {
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">self</span> = [<span class="hljs-keyword">super</span> init]) {
        <span class="hljs-comment">// Initialize self.</span>
    }
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>;
}
</code></pre>
<hr>
<h2 id="2">2.练习</h2>
<ul>
<li>要求通过Person类创建出来的人初始化值都是10岁。</li>
</ul>
<pre><code class="lang-objc"><span class="hljs-class"><span class="hljs-keyword">@implementation</span> <span class="hljs-title">Person</span></span>

- (instancetype)init
{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">self</span> = [<span class="hljs-keyword">super</span> init]) {
        _age = <span class="hljs-number">10</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>;
}
<span class="hljs-keyword">@end</span>
</code></pre>
<ul>
<li>让学生继承人类,要求学生对象初始化之后,年龄是10,学号是1,怎么办?</li>
</ul>
<pre><code class="lang-objc"><span class="hljs-class"><span class="hljs-keyword">@implementation</span> <span class="hljs-title">Person</span></span>

- (instancetype)init
{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">self</span> = [<span class="hljs-keyword">super</span> init]) {
        _age = <span class="hljs-number">10</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>;
}
<span class="hljs-keyword">@end</span>

<span class="hljs-class"><span class="hljs-keyword">@implementation</span> <span class="hljs-title">Student</span></span>

- (instancetype)init
{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">self</span> = [<span class="hljs-keyword">super</span> init]) {
        _no = <span class="hljs-number">1</span>;
    }
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">self</span>;
}
<span class="hljs-keyword">@end</span>
</code></pre>
<h2 id="3">3.构造方法使用注意</h2>
<ul>
<li>子类拥有的成员变量包括自己的成员变量以及从父类继承而来的成员变量,在重写构造方法的时候应该首先对从父类继承而来的成员变量先进行初始化。<ul>
<li>原则:先初始化父类的,再初始化子类的。<ul>
<li>先调用父类的构造方法[super init];</li>
<li>再进行子类内部成员变量的初始化。</li>
</ul>
</li>
</ul>
</li>
<li><p>千万不要把<code>self = [super init]</code>写成self <code>==</code> [super init]</p>
</li>
<li><p>重写构造方法的目的:为了让对象方法一创建出来,成员变量就会有一些固定的值。</p>
</li>
</ul>
<h2 id="4instancetype">4.instancetype的作用</h2>
<ul>
<li>instancetype与id相似，不过instancetype只能作为方法返回值，它会进行类型检查，如果创建出来的对象，赋值了不相干的对象就会有一个警告信息，防止出错。</li>
</ul>
<pre><code class="lang-objc"><span class="hljs-comment">// init此时返回值是id</span>
<span class="hljs-built_in">NSString</span> *str = [[Person alloc] init];
<span class="hljs-comment">// Person并没有length方法, 但是id是动态类型, 所以编译时不会报错</span>
<span class="hljs-built_in">NSLog</span>(<span class="hljs-string">@"length = %i"</span>, str<span class="hljs-variable">.length</span>);
</code></pre>
<pre><code class="lang-objc"><span class="hljs-comment">// init此时返回值是instancetype</span>
<span class="hljs-comment">// 由于instancetype它会进行类型检查, 所以会报警告</span>
<span class="hljs-built_in">NSString</span> *str = [[Person alloc] init];
<span class="hljs-built_in">NSLog</span>(<span class="hljs-string">@"length = %i"</span>, str<span class="hljs-variable">.length</span>);
</code></pre>
<pre><code class="lang-objc">instancetype *p = [[person alloc] init];
<span class="hljs-comment">// 错误写法instancetype只能作为返回值</span>
</code></pre>

                    
                    </section>
                
                
                </div>
            </div>
        </div>

        
        <a href="./new/README.html" class="navigation navigation-prev " aria-label="Previous page: new方法实现原理"><i class="fa fa-angle-left"></i></a>
        
        
        <a href="./10.html" class="navigation navigation-next " aria-label="Next page: 自定义构造方法"><i class="fa fa-angle-right"></i></a>
        
    </div>
</div>

        
<script src="gitbook/app.js"></script>

    
    <script src="https://cdn.mathjax.org/mathjax/2.4-latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    

    
    <script src="gitbook/plugins/gitbook-plugin-mathjax/plugin.js"></script>
    

<script>
require(["gitbook"], function(gitbook) {
    var config = {"fontSettings":{"theme":null,"family":"sans","size":2}};
    gitbook.start(config);
});
</script>

        
    </body>
    
</html>
